#!/usr/bin/env bash
set -e

################## 可自定义变量 ##################
WORKDIR=/opt/pptp-vpn
# 使用命令行参数或默认值
VPN_USER=${1:-username}        # 如果未传入参数1，默认username
VPN_PASS=${2:-password}        # 如果未传入参数2，默认password
TIMEZONE=Asia/Shanghai         # 时区设置
IMAGE=swr.cn-east-2.myhuaweicloud.com/suyuansoft/hub:vpn-pptp       # PPTP VPN服务器镜像
###################################################

echo "==> 使用配置："
echo "    VPN用户名: $VPN_USER"
echo "    VPN密码: $VPN_PASS"
echo "    TIMEZONE: $TIMEZONE"
echo "    WORKDIR: $WORKDIR"

echo "==> 1. 设置宿主机时区为 $TIMEZONE"
sudo timedatectl set-timezone "$TIMEZONE" || {
  sudo ln -sf "/usr/share/zoneinfo/$TIMEZONE" /etc/localtime
  echo "$TIMEZONE" | sudo tee /etc/timezone
}

echo "==> 2. 创建工作目录 $WORKDIR"
sudo mkdir -p "$WORKDIR" && cd "$WORKDIR"

echo "==> 3. 创建 chap-secrets 认证文件"
cat <<EOF | sudo tee chap-secrets >/dev/null
# Secrets for authentication using PAP
# client    server      secret      acceptable local IP addresses
$VPN_USER   *           $VPN_PASS    *
EOF

echo "==> 4. 生成 docker-compose.yml (使用host网络模式)"
cat <<EOF | sudo tee docker-compose.yml >/dev/null
version: '2.2'
services:
  pptp:
    image: ${IMAGE}
    container_name: pptp-vpn
    restart: unless-stopped
    privileged: true
    network_mode: host
    volumes:
      - ${WORKDIR}/chap-secrets:/etc/ppp/chap-secrets
      - /etc/localtime:/etc/localtime:ro
    environment:
      - TZ=${TIMEZONE}
EOF

echo "==> 5. 加载必要的内核模块"
sudo modprobe nf_conntrack_pptp || true
sudo modprobe ppp_mppe || true
sudo modprobe ppp_deflate || true

echo "==> 6. 配置系统参数"
sudo sysctl -w net.ipv4.ip_forward=1
sudo sysctl -w net.ipv4.conf.all.accept_redirects=0
sudo sysctl -w net.ipv4.conf.all.send_redirects=0
sudo sysctl -w net.ipv4.conf.default.accept_redirects=0
sudo sysctl -w net.ipv4.conf.default.send_redirects=0

echo "==> 7. 启动VPN容器"
sudo docker-compose up -d

echo "==> 8. 等待服务初始化(约10秒)..."
sleep 10

echo "======================================================"
echo "PPTP VPN 已成功部署！"
echo "  服务器地址: $(curl -s 4.ipw.cn || curl -s http://ip.3322.net)"
echo "  用户名: ${VPN_USER}"
echo "  密码: ${VPN_PASS}"
echo "  协议: PPTP"
echo ""
echo "客户端连接注意事项:"
echo "  * 需要开放TCP端口: 1723"
echo "  * 需要开放GRE协议 (IP协议47)"
echo "  * Windows客户端可能需要修改注册表:"
echo "    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]"
echo "    \"EnablePacketForwarding\"=dword:00000001"
echo "    \"EnableICMPRedirect\"=dword:00000000"
echo ""
echo "管理说明:"
echo "  1. 添加/修改用户:"
echo "    编辑 ${WORKDIR}/chap-secrets 文件"
echo "    格式: '用户名 * 密码 *' (每行一个用户)"
echo "  2. 用户更改后无需重启容器"
echo "  3. 查看日志: docker logs pptp-vpn"
echo "  4. 重启服务: docker restart pptp-vpn"
echo "======================================================"